<?
require("../../mysql.config.inc");
$mysqli = new mysqli($host,$username,$password,$db);
		
if(!isset($_GET['pid'])){
	$_GET['pid'] = 1;
}elseif($_GET['pid'] <= 1){
	$_GET['pid'] = 1;
	$firstPhoto = true;
}

if(isset($_GET['aid'])){
	$maxPidResult = $mysqli->query("SELECT MAX(pid) FROM Photos NATURAL JOIN AlbumIn WHERE aid = ".$_GET['aid']);
	$maxPid= $maxPidResult->fetch_array();
	
	$minPidResult = $mysqli->query("SELECT MIN(pid) FROM Photos NATURAL JOIN AlbumIn WHERE aid = ".$_GET['aid']);
	$minPid= $minPidResult->fetch_array();
	
}else{
	$maxPidResult = $mysqli->query("SELECT MAX(pid) FROM Photos");
	$maxPid= $maxPidResult->fetch_array();
	
	$minPidResult = $mysqli->query("SELECT MIN(pid) FROM Photos");
	$minPid= $maxPidResult->fetch_array();
}

//Checks to see if the GET id number is greater than the highest actual PhotoID and then
//sets it to the actual max if it is. 
if($_GET['pid'] >= $maxPid[0]){
	$_GET['pid'] = $maxPid[0];
	$lastPhoto = true;
}elseif($_GET['pid'] <= $minPid[0]){
	$_GET['pid'] = $minPid[0];
	$firstPhoto = true;
}

if(isset($_GET['aid'])){
	$result = $mysqli->query("SELECT pid FROM Photos NATURAL JOIN AlbumIn WHERE aid =".$_GET['aid']);
}else{
	$result = $mysqli->query("SELECT pid FROM Photos");
}

while($pidArrayLine = $result->fetch_assoc()){
	$pidArray[] = $pidArrayLine['pid'];
}

if(!in_array($_GET['pid'],$pidArray)){
	getPid();
}

//If the GET id isn't an actual id but isn't over or under the highest one, adds
//1 or subtracts 1 until it is in the array.
function getPid(){
	require("../../mysql.config.inc");
	$mysqli = new mysqli($host,$username,$password,$db);

	if(isset($_GET['aid'])){
		$result = $mysqli->query("SELECT pid FROM Photos NATURAL JOIN AlbumIn WHERE aid =".$_GET['aid']);
	}else{
		$result = $mysqli->query("SELECT pid FROM Photos");
	}
	$mysqli->close();
	
	while($pidArrayLine = $result->fetch_assoc()){
		$pidArray[] = $pidArrayLine['pid'];
	}
	if(in_array($_GET['pid'],$pidArray)){
		return;
	}elseif(!in_array($_GET['pid'],$pidArray) && isset($_GET['back'])){
		$_GET['pid'] = $_GET['pid'] - 1;
		getPid();
	}else{
		$_GET['pid'] = $_GET['pid'] + 1;
		getPid();
	}
	
}

$result = $mysqli->query("SELECT* FROM Photos WHERE pid = ".$_GET['pid']);

while($photos = $result->fetch_assoc()){
	
	print("var link = \"".$photos['Link']."\";\n");
	print("var getCaption = \"".$photos['Caption']."\";\n");
	print("var getpid = ".$_GET['pid'].";\n");
	
	$link = "../".$photos['Link'];
	$imageSize = getimagesize($link);
	$imageWidth = $imageSize[0];
	if($imageWidth < 950){
		print("var imageWidth = $imageWidth;\n");
		print("var attribute = \"photoDisplay\";\n");
	}else{
		print("var imageWidth = \"950\";\n");
		print("var attribute = \"viewPhoto\";\n");
	}
	
	
}
$mysqli->close();

?>